<?php

class TagsController extends AppController{
    var $name='Tags';
    var $uses = array('Tag','Subject');
    function beforeFilter() {
       parent::beforeFilter();
        $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'admin_index');
        $this->Auth->allow('tag_tree','tag_tree2','f_server','search');
        
    }
    function admin_index(){
        
        if(!$this->Access->check('Tag', 'read')) {
            $this->Session->setFlash('You dont have permissions to View this content');
            $this->redirect(array('controller'=>'users','action'=>'admin_index'));
        } 
        $this->layout='ajax';
    }
    function admin_server() {
        App::import('Vendor', 'config');
        $jstree = new json_tree();
        if(isset($_GET["reconstruct"])) {
            $jstree->_reconstruct();
            die();
        }
        if(isset($_GET["analyze"])) {
            echo $jstree->_analyze();
            die();
        }

        if($_REQUEST["operation"] && strpos("_", $_REQUEST["operation"]) !== 0 && method_exists($jstree, $_REQUEST["operation"])) {
	header("HTTP/1.0 200 OK");
	header('Content-type: text/json; charset=utf-8');
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	echo $jstree->{$_REQUEST["operation"]}($_REQUEST);
	die();
        }
        header("HTTP/1.0 404 Not Found"); 
    }
    
    function f_server(){
        App::import('Vendor', 'config');
        $jstree = new json_tree();
        if(isset($_GET["reconstruct"])) {
            $jstree->_reconstruct();
            die();
        }
        if(isset($_GET["analyze"])) {
            echo $jstree->_analyze();
            die();
        }

        if($_REQUEST["operation"] && strpos("_", $_REQUEST["operation"]) !== 0 && method_exists($jstree, $_REQUEST["operation"])) {
	header("HTTP/1.0 200 OK");
	header('Content-type: text/json; charset=utf-8');
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	//echo '[{"attr":{"id":"node_2","rel":"drive"},"data":"C:","state":"closed"},{"attr":{"id":"node_6","rel":"drive"},"data":"D:","state":""}]';//$jstree->{$_REQUEST["operation"]}($_REQUEST);
//        echo method_exists($jstree, $_REQUEST["operation"]);
        echo $jstree->{$_REQUEST["operation"]}($_REQUEST);
	die();
        }
        header("HTTP/1.0 404 Not Found");
    }
    
    function tag_tree2(){
        $this->set('title_for_layout', 'Rate The Universe - Tag tree');
        $tag_tree_list = $this->Tag->generatetreelist(array('Tag.level > ' => '0'),'{n}.Tag.id','{n}.Tag.title');
        
        $tag_tree = $this->pre_parse_tree_list2($tag_tree_list);
//        $this->set('tag_tree',$tag_tree);
//        var_dump($tag_tree[0]);die();
        $this->set('tag_tree',$this->draw_tag_tree($tag_tree[0]));  
    }
    
    function tag_tree(){
        $this->set('title_for_layout', 'Rate The Universe - Tag tree');
        $tag_tree_list = $this->Tag->generatetreelist(array('Tag.level > ' => '0'),'{n}.Tag.id','{n}.Tag.title');              
    }
    
    function search($tag_id=null){
        $this->set('title_for_layout', 'Rate The Universe - Search Tag Tree results');
        Configure::write('debug', -1);
        
        if(isset($_GET['tag_id']) && !empty($_GET['tag_id'])){
            $tag_id = $_GET['tag_id'];
            $_SESSION['search_tag'] = $tag_id;
        }else
            if(isset($_SESSION['search_tag']))
                $tag_id = $_SESSION['search_tag'];
            else
                $this->redirect(array('controller'=>'tags','action'=>'tag_tree'));
        
        $childs = $this->Tag->children($tag_id, false, 'id', 'level ASC');
        $arr_tag_ids = array();
        foreach ($childs as $values) {
            $arr_tag_ids[] = $values['Tag']['id'];
        }
        
        
            $tmp = array();
            for($i=0;$i<count($arr_tag_ids);$i++){
//                $tmp[] = '^'.$arr_tag_ids[$i].'$';
                $tmp[] = ','.$arr_tag_ids[$i].',';
//                $tmp[] = '^'.$arr_tag_ids[$i].'$'."|^$arr_tag_ids[$i],"."|,$arr_tag_ids[$i]$"."|,$arr_tag_ids[$i],";
            }
            
            $tag_ids = implode('|', $tmp);
            if ($tag_ids == '') {
                $tag_ids = $tag_id;//$tag_ids = ','.$tag_id.',';
            }

            $this->Subject->unbindModel(array('hasMany' => array('SubjectRate', 'Comment', 'Attribute', 'SubjectAdjectives', 'Subjectredirect')));
            $conditions = array('Subject.image !='=>'','Subject.17+'=>'0','Subject.status'=>'1');
            if(isset($tag_ids))
                $conditions['Subject.tag_ids regexp'] = "('$tag_ids')";
            $this->paginate = array('fields' => array('Subject.subject','Subject.desc','Subject.id','Subject.image','Subject.tag_ids'),
                                    'conditions' => $conditions,
                                    'recursive' => 0,
                                    'limit' => 30,
                                    'order' => 'Subject.subject'
                                    );
            $data = $this->paginate('Subject');
            $this->set(compact('data'));
            $this->set(compact('tag_id'));
    }
    
    private function draw_tag_tree($tag_tree){
        if($tag_tree['parent_index'] == -1)
        {
            $start_str = '<ul id="tree">';
            $str = '';
            foreach($tag_tree['children'] as $child)
            {
                $str .= $this->draw_tag_tree($child);
            }
            $end_str = '</ul>';
            return $start_str.$str.$end_str;
        }
        else
        if(empty($tag_tree['children']))
        {	
            $f_add_strong = "";
            $l_add_strong = "";
            if($tag_tree['parent_index'] == 0)
            {
                    $f_add_strong = "<strong>";
                    $l_add_strong = "</strong>";
            }
            return "<li><a href='#'>$f_add_strong" . $tag_tree['title'] . "$l_add_strong</a></li>";
        }
        else
        {
            $f_add_strong = "";
            $l_add_strong = "";
            if($tag_tree['parent_index'] == 0)
            {
                    $f_add_strong = "<strong>";
                    $l_add_strong = "</strong>";
            }
            $start_str = "<li><a href='#'>$f_add_strong" . $tag_tree['title'] . "$l_add_strong</a><ul>";
            $str = "";
            foreach($tag_tree['children'] as $child)
            {
                $str .= $this->draw_tag_tree($child);
            }
            $end_str = "</ul></li>";
            return $start_str.$str.$end_str;
        }
    }
    //apply parent_id
    private function pre_parse_tree_list2($tree_list){
        if(empty($tree_list) || !is_array($tree_list))
            return false;
        $pre_tree = $this->pre_parse_tree_list1($tree_list);
        if(!$pre_tree)
            return false;
        
        $curr_lvl_id = array();
        for($i=0;$i<=1000;$i++)
            $curr_lvl_id[$i] = 0;
        $curr_lvl_index = array();
        for($i=0;$i<=1000;$i++)
            $curr_lvl_index[$i] = -1;
       
        for($i=0;$i<count($pre_tree);$i++)
        {
            $pre_tree[$i]['children'] = array();
            $pre_tree[$i]['parent_id'] = $curr_lvl_id[$pre_tree[$i]['level']-1];
            $pre_tree[$i]['parent_index'] = $curr_lvl_index[$pre_tree[$i]['level']-1];
            $curr_lvl_id[$pre_tree[$i]['level']] = $pre_tree[$i]['id'];
            $curr_lvl_index[$pre_tree[$i]['level']] = $i;
            
//            if($pre_tree[$i]['parent_index'] != -1)
//                $pre_tree[$pre_tree[$i]['parent_index']]['children'][] = $pre_tree[$i];
        }
        
        for($i=count($pre_tree)-1;$i>0;$i--)
            if($pre_tree[$i]['parent_index'] != -1)
                $pre_tree[$pre_tree[$i]['parent_index']]['children'][] = $pre_tree[$i];
        
        while(count($pre_tree)>1){
            unset($pre_tree[count($pre_tree)-1]);
        }
        
        return $pre_tree;
    }
    //apply level for tag
    //change title (after explode '_')
    private function pre_parse_tree_list1($tree_list){
        if(empty($tree_list) || !is_array($tree_list))
            return false;
        
        $pre_tree = array();
        $i=0;
        foreach($tree_list as $key => $value)
        {
            $pre_tree[$i] = array();
            $pre_tree[$i]['id'] = $key;
            $explode_title = explode('_',$value);
            if(count($explode_title)==1)
            {
                $pre_tree[$i]['title'] = $value;
                $pre_tree[$i]['level'] = 1;
            }
            else
            {
                $pre_tree[$i]['title'] = $explode_title[count($explode_title)-1];
                $pre_tree[$i]['level'] = count($explode_title);
            }
            
            $i++;
        }
        return $pre_tree;
    }
}
?>